{% extends 'base.html' %}

{% block title %}数据整合{% endblock %}

{% block content %}
<div class="card mb-4">
    <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
        <h4 class="mb-0">种植数据与环境数据整合</h4>
        <div>
            <button type="button" class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#exportModal">
                <i class="fas fa-file-export"></i> 导出数据
            </button>
            <button type="button" class="btn btn-light btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#analysisModal">
                <i class="fas fa-chart-bar"></i> 数据分析
            </button>
        </div>
    </div>
    <div class="card-body">
        <!-- 添加搜索表单 -->
        <form method="get" class="mb-4">
            <div class="row g-3">
                <div class="col-md-3">
                    <input type="text" class="form-control" name="search_region" value="{{ search_region }}" placeholder="搜索区域...">
                </div>
                <div class="col-md-2">
                    <input type="date" class="form-control" name="date_from" value="{{ date_from }}" placeholder="开始日期">
                </div>
                <div class="col-md-2">
                    <input type="date" class="form-control" name="date_to" value="{{ date_to }}" placeholder="结束日期">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">搜索</button>
                </div>
                <div class="col-md-2">
                    <a href="{{ url_for('cleaning.data_integration') }}" class="btn btn-secondary w-100">重置</a>
                </div>
            </div>
        </form>

        <!-- 现有的表格代码保持不变 -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>区域</th>
                        <th>日期</th>
                        <th>总种植面积(亩)</th>
                        <th>种植记录数</th>
                        <th>温度(℃)</th>
                        <th>降雨量(mm)</th>
                        <th>土壤类型</th>
                        <th>光照强度(lux)</th>
                    </tr>
                </thead>
                <tbody>
                    {% for item in integrated_data %}
                    <tr>
                        <td>{{ item.region }}</td>
                        <td>{{ item.planting_date.strftime('%Y-%m-%d') }}</td>
                        <td>{{ "%.2f"|format(item.total_area|float) }}</td>
                        <td>{{ item.planting_count }}</td>
                        <td>{{ "%.1f"|format(item.temperature|float) if item.temperature else '-' }}</td>
                        <td>{{ "%.1f"|format(item.rainfall|float) if item.rainfall else '-' }}</td>
                        <td>{{ item.soil_type or '-' }}</td>
                        <td>{{ "%.1f"|format(item.light_intensity|float) if item.light_intensity else '-' }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        <!-- 添加分页导航 -->
        {% if pagination and pagination.pages > 1 %}
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center">
                <li class="page-item {% if not pagination.has_prev %}disabled{% endif %}">
                    <a class="page-link" href="{% if pagination.has_prev %}{{ url_for('cleaning.data_integration', page=pagination.prev_num, search_region=search_region, date_from=date_from, date_to=date_to) }}{% else %}#{% endif %}">
                        上一页
                    </a>
                </li>
                
                {% for page in pagination.iter_pages(left_edge=2, left_current=2, right_current=3, right_edge=2) %}
                    {% if page %}
                        <li class="page-item {% if page == pagination.page %}active{% endif %}">
                            <a class="page-link" href="{{ url_for('cleaning.data_integration', page=page, search_region=search_region, date_from=date_from, date_to=date_to) }}">
                                {{ page }}
                            </a>
                        </li>
                    {% else %}
                        <li class="page-item disabled">
                            <span class="page-link">...</span>
                        </li>
                    {% endif %}
                {% endfor %}
                
                <li class="page-item {% if not pagination.has_next %}disabled{% endif %}">
                    <a class="page-link" href="{% if pagination.has_next %}{{ url_for('cleaning.data_integration', page=pagination.next_num, search_region=search_region, date_from=date_from, date_to=date_to) }}{% else %}#{% endif %}">
                        下一页
                    </a>
                </li>
            </ul>
        </nav>
        {% endif %}
    </div>
</div>

<div class="card mt-4">
    <div class="card-header bg-primary text-white">
        <h4 class="mb-0">数据说明</h4>
    </div>
    <div class="card-body">
        <ul class="list-unstyled">
            <li class="mb-2">
                <strong>总种植面积：</strong>
                同一区域同一日期的所有种植记录的面积总和
            </li>
            <li class="mb-2">
                <strong>种植记录数：</strong>
                同一区域同一日期的种植记录数量
            </li>
            <li class="mb-2">
                <strong>环境数据：</strong>
                与种植日期对应的环境监测数据，包括温度、降雨量、土壤类型和光照强度
            </li>
            <li class="mb-2">
                <strong>数据匹配：</strong>
                只显示种植数据和环境数据在同一区域、同一日期的记录
            </li>
        </ul>
    </div>
</div>

<div class="card mt-4">
    <div class="card-header bg-primary text-white">
        <h4 class="mb-0">数据分析建议</h4>
    </div>
    <div class="card-body">
        <ul class="list-unstyled">
            <li class="mb-2">
                <i class="fas fa-chart-line text-primary"></i>
                <strong>趋势分析：</strong>
                观察不同环境条件下的种植面积变化
            </li>
            <li class="mb-2">
                <i class="fas fa-map-marker-alt text-primary"></i>
                <strong>区域分布：</strong>
                分析各区域的种植密度与环境因素的关系
            </li>
            <li class="mb-2">
                <i class="fas fa-thermometer-half text-primary"></i>
                <strong>环境影响：</strong>
                研究温度、降雨量等环境因素对种植规模的影响
            </li>
            <li class="mb-2">
                <i class="fas fa-calendar-alt text-primary"></i>
                <strong>季节性分析：</strong>
                研究种植活动的季节性规律及其与环境条件的关联
            </li>
        </ul>
    </div>
</div>

<!-- 添加导出数据模态框 -->
<div class="modal fade" id="exportModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">导出数据</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="{{ url_for('cleaning.export_integrated_data') }}" method="post">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">导出格式</label>
                        <select class="form-select" name="export_format" required>
                            <option value="excel">Excel (.xlsx)</option>
                            <option value="csv">CSV (.csv)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">数据范围</label>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="export_range" value="all" id="exportAll" checked>
                            <label class="form-check-label" for="exportAll">
                                所有数据
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="export_range" value="filtered" id="exportFiltered">
                            <label class="form-check-label" for="exportFiltered">
                                当前筛选结果
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">导出</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 修改数据分析模态框部分 -->
<div class="modal fade" id="analysisModal" tabindex="-1" role="dialog" aria-labelledby="analysisModalLabel">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="analysisModalLabel">数据分析</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
                <!-- 添加加载提示 -->
                <div id="chartLoading" class="text-center d-none">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在加载分析数据...</p>
                </div>
                
                <!-- 添加错误提示 -->
                <div id="chartError" class="alert alert-danger d-none" role="alert">
                    <i class="fas fa-exclamation-circle"></i>
                    <span id="errorMessage">加载数据失败</span>
                </div>

                <ul class="nav nav-tabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="trend-tab" data-bs-toggle="tab" data-bs-target="#trendAnalysis" type="button" role="tab" aria-controls="trendAnalysis" aria-selected="true">趋势分析</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="region-tab" data-bs-toggle="tab" data-bs-target="#regionAnalysis" type="button" role="tab" aria-controls="regionAnalysis" aria-selected="false">区域分析</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="environment-tab" data-bs-toggle="tab" data-bs-target="#environmentAnalysis" type="button" role="tab" aria-controls="environmentAnalysis" aria-selected="false">环境分析</button>
                    </li>
                </ul>
                <div class="tab-content mt-3">
                    <div class="tab-pane fade show active" id="trendAnalysis" role="tabpanel" aria-labelledby="trend-tab">
                        <div id="trendChart" style="height: 400px;"></div>
                    </div>
                    <div class="tab-pane fade" id="regionAnalysis" role="tabpanel" aria-labelledby="region-tab">
                        <div id="regionChart" style="height: 400px;"></div>
                    </div>
                    <div class="tab-pane fade" id="environmentAnalysis" role="tabpanel" aria-labelledby="environment-tab">
                        <div id="environmentChart" style="height: 400px;"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
{{ super() }}
<!-- 确保先加载ECharts -->
<script src="{{ url_for('static', filename='js/echarts.min.js') }}"></script>
<!-- 添加调试信息 -->
<script>
console.log('页面加载完成，准备初始化图表功能...');

// 等待文档完全加载
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成');
    
    // 确保ECharts已加载
    if (typeof echarts === 'undefined') {
        console.error('ECharts未正确加载！');
        return;
    }
    console.log('ECharts已加载');

    // 初始化图表对象
    let charts = {
        trend: null,
        region: null,
        environment: null
    };

    // 初始化图表函数
    function initCharts() {
        try {
            console.log('开始初始化图表...');
            const chartContainers = {
                trend: document.getElementById('trendChart'),
                region: document.getElementById('regionChart'),
                environment: document.getElementById('environmentChart')
            };

            // 检查容器是否存在
            Object.entries(chartContainers).forEach(([key, container]) => {
                if (!container) {
                    console.error(`${key}图表容器未找到`);
                    return;
                }
                if (!charts[key]) {
                    console.log(`初始化${key}图表...`);
                    charts[key] = echarts.init(container);
                    console.log(`${key}图表初始化完成`);
                }
            });
        } catch (error) {
            console.error('图表初始化失败:', error);
        }
    }

    // 监听模态框事件
    const analysisModal = document.getElementById('analysisModal');
    if (!analysisModal) {
        console.error('未找到分析模态框元素');
        return;
    }

    // 模态框显示前
    analysisModal.addEventListener('show.bs.modal', function() {
        console.log('模态框即将显示');
    });

    // 模态框完全显示后
    analysisModal.addEventListener('shown.bs.modal', function() {
        console.log('模态框已完全显示');
        // 确保DOM已完全渲染后再初始化图表
        setTimeout(() => {
            console.log('开始初始化和加载数据...');
            initCharts();
            loadAnalysisData();
        }, 300);
    });

    // 加载分析数据
    function loadAnalysisData() {
        const loadingEl = document.getElementById('chartLoading');
        const errorEl = document.getElementById('chartError');
        
        if (!loadingEl || !errorEl) {
            console.error('未找到加载或错误提示元素');
            return;
        }

        // 显示加载状态
        loadingEl.classList.remove('d-none');
        errorEl.classList.add('d-none');
        
        console.log('开始获取分析数据...');
        fetch("{{ url_for('cleaning.get_analysis_data') }}")
            .then(response => {
                console.log('服务器响应状态:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('收到数据:', data);
                loadingEl.classList.add('d-none');
                updateCharts(data);
            })
            .catch(error => {
                console.error('数据加载失败:', error);
                loadingEl.classList.add('d-none');
                errorEl.classList.remove('d-none');
                document.getElementById('errorMessage').textContent = 
                    error.message || '获取分析数据失败，请稍后重试';
            });
    }

    // 更新图表
    function updateCharts(data) {
        console.log('开始更新图表...');
        try {
            // 趋势分析图表
            if (charts.trend) {
                console.log('更新趋势图表...');
                const trendOption = {
                    title: { 
                        text: '种植面积趋势分析',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(params) {
                            const date = params[0].value[0];
                            const area = params[0].value[1].toFixed(2);
                            return `日期：${date}<br/>面积：${area}亩`;
                        }
                    },
                    grid: {
                        left: '5%',
                        right: '5%',
                        bottom: '10%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'time',
                        name: '日期',
                        axisLabel: {
                            formatter: '{yyyy}-{MM}-{dd}'
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '种植面积(亩)'
                    },
                    series: [{
                        name: '种植面积',
                        type: 'line',
                        data: data.trend_data,
                        smooth: true,
                        symbolSize: 6
                    }]
                };
                charts.trend.setOption(trendOption);
            }

            // 区域分析图表
            if (charts.region) {
                console.log('更新区域图表...');
                const regionOption = {
                    title: { 
                        text: '区域种植分布分析',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{b}: {c}亩 ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        top: 'middle'
                    },
                    series: [{
                        type: 'pie',
                        radius: ['40%', '70%'],
                        center: ['60%', '50%'],
                        data: data.region_data,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        label: {
                            show: true,
                            formatter: '{b}: {c}亩'
                        }
                    }]
                };
                charts.region.setOption(regionOption);
            }

            // 环境分析图表
            if (charts.environment) {
                console.log('更新环境图表...');
                const environmentOption = {
                    title: { 
                        text: '温度与种植面积关系分析',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(params) {
                            return `温度：${params[0].name}℃<br/>平均面积：${params[0].value.toFixed(2)}亩`;
                        }
                    },
                    grid: {
                        left: '5%',
                        right: '5%',
                        bottom: '10%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        name: '温度(℃)',
                        data: data.environment_data.categories,
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '平均种植面积(亩)'
                    },
                    series: [{
                        type: 'bar',
                        data: data.environment_data.values,
                        itemStyle: {
                            color: '#3398DB'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}亩'
                        }
                    }]
                };
                charts.environment.setOption(environmentOption);
            }
            console.log('所有图表更新完成');
        } catch (error) {
            console.error('更新图表时出错:', error);
            document.getElementById('chartError').classList.remove('d-none');
            document.getElementById('errorMessage').textContent = '图表渲染失败，请刷新页面重试';
        }
    }

    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        console.log('窗口大小改变，调整图表大小');
        Object.entries(charts).forEach(([key, chart]) => {
            if (chart) {
                chart.resize();
            }
        });
    });

    console.log('图表功能初始化完成');
});
</script>
{% endblock %} 